package com.example.demo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
import java.util.Optional;

@Component
public class JwtToken {

    private static String Jwtkey;
    private static Integer expiresTimeIn;

    @Value("${security.jwt-key}")
    public void setJewKey(String jwtkey){
        JwtToken.Jwtkey =jwtkey;
    }
    @Value("${security.token-expired-in}")
    public void setExpiresTimeIN(Integer expiresTimeIn){
        JwtToken.expiresTimeIn=expiresTimeIn;
    }

    public static String makeToken(Long uid ,Integer scope) {

        return JwtToken.getToken(uid,scope);
    }
    public static String makeToken(Long uid) {

        return JwtToken.getToken(uid,1);
    }

    private static String getToken (Long uid ,Integer scope){
        //jwt  的相关库
        //jjwt  auth0
        Algorithm algorithm = Algorithm.HMAC256(JwtToken.Jwtkey);

        String jwt = JWT.create()
                .withClaim("uid",uid)
                .withClaim("scope",scope)//写入信息
                .withExpiresAt(new Date(2032,1,1))//写入过期时间//Todo 优化时间设定
                //.withIssuedAt()  签发时间  可写可不写
                 .sign(algorithm);

        return jwt ;

    }


    public static Optional<Map<String, Claim>> getClaims(String token){//用于解析和验证jwt
        Algorithm algorithm =Algorithm.HMAC256(JwtToken.Jwtkey);
        JWTVerifier jwtVerifier =JWT.require(algorithm).build();
        DecodedJWT decoderjwt=null;
        try {
            decoderjwt = jwtVerifier.verify(token);

        }catch(Exception e){
            //return null;//可以用optional来改造
            return Optional.empty();

        }

        return Optional.of(decoderjwt.getClaims());


    }
    /*
    public static Map<String, Claim> getClaims(String token){//用于解析和验证jwt
        Algorithm algorithm =Algorithm.HMAC256(JwtToken.Jwtkey);
        JWTVerifier jwtVerifier =JWT.require(algorithm).build();
        DecodedJWT decoderjwt=null;
        try {
            decoderjwt = jwtVerifier.verify(token);

        }catch(Exception e){
            return null;//可以用optional来改造
        }

        return decoderjwt.getClaims();


    }*/



    public static Boolean verifyToken(String token ){
        try{
            Algorithm algorithm = Algorithm.HMAC256(JwtToken.Jwtkey);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);

        }
        catch(Exception e){
            return false ;
        }
        return true ;

    }


}
